package com.hooker.hook;

import androidx.annotation.NonNull;

import com.hooker.common.StringUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Rule {
    private String name;
    private String className;
    private String method;
    private List<String> params;
    private String param;
    private static final String SPLITSTR = "---";

    public Rule() {
    }

    public Rule(String className, String method) {
        this.className = className;
        this.method = method;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public List<String> getParams() {
        if (params == null) {
            params = new ArrayList<>();
        }
        return params;
    }

    public void setParams(List<String> params) {
        this.params = params;
    }

    public String getParam() {
        return param;
    }

    public void setParam(String param) {
        this.param = param;
        update();
    }

    public void update() {
        if (param != null && !"".equals(param)) {
            try {
                String[] paramList = param.split(SPLITSTR);
                params = Arrays.asList(paramList);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @NonNull
    @Override
    public String toString() {
        JSONObject json = new JSONObject();
        try {
            json.put("name", name);
            json.put("className", className);
            json.put("method", method);
            json.put("param", getParamJson());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
    }

    private String getParamJson() {
        StringBuilder builder = new StringBuilder();
        if (params != null && params.size() > 0) {
            StringUtil.join(builder, params, SPLITSTR);
        }
        return builder.toString();
    }

    //获取方法
    public String getMethodWithParam() {
        StringBuilder builder = new StringBuilder();
        builder.append(method);
        builder.append("(");
        if (params != null && params.size() > 0) {
            StringUtil.join(builder, params, ",");
        }
        builder.append(")");
        return builder.toString();
    }
}
